//
//  zhuanAppDelegate.m
//  zhuan
//
//  Created by zhao ys on 5/27/11.
//  Copyright __MyCompanyName__ 2011. All rights reserved.
//

#import "cocos2d.h"

#import "zhuanAppDelegate.h"
#import "GameConfig.h"
#import "HelloWorldLayer.h"
#import "RootViewController.h"
#import "SoundManager.h"
#import "pauseLayer.h"
#import "playLayer.h"
#import "GameCenter.h"

@implementation zhuanAppDelegate

@synthesize window;

- (void) removeStartupFlicker
{
	//
	// THIS CODE REMOVES THE STARTUP FLICKER
	//
	// Uncomment the following code if you Application only supports landscape mode
	//
#if GAME_AUTOROTATION == kGameAutorotationUIViewController

//	CC_ENABLE_DEFAULT_GL_STATES();
//	CCDirector *director = [CCDirector sharedDirector];
//	CGSize size = [director winSize];
//	CCSprite *sprite = [CCSprite spriteWithFile:@"Default.png"];
//	sprite.position = ccp(size.width/2, size.height/2);
//	sprite.rotation = -90;
//	[sprite visit];
//	[[director openGLView] swapBuffers];
//	CC_ENABLE_DEFAULT_GL_STATES();
	
#endif // GAME_AUTOROTATION == kGameAutorotationUIViewController	
}

/*
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
    // Override point for customization after application launch.
	[NSThread sleepForTimeInterval:2.0];
	
	// Set the view controller as the window's root view controller and display.
    //window.rootViewController = viewController;
	//[self.window makeKeyAndVisible];
    return YES;
}
*/
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
	[NSThread sleepForTimeInterval:1.0];

	// Init the window
	window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
	
	// Try to use CADisplayLink director
	// if it fails (SDK < 3.1) use the default director
	if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
		[CCDirector setDirectorType:kCCDirectorTypeDefault];
	
	
	CCDirector *director = [CCDirector sharedDirector];
	
	// Init the View Controller
	viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
	viewController.wantsFullScreenLayout = YES;
	
	//
	// Create the EAGLView manually
	//  1. Create a RGB565 format. Alternative: RGBA8
	//	2. depth format of 0 bit. Use 16 or 24 bit for 3d effects, like CCPageTurnTransition
	//
	//
	EAGLView *glView = [EAGLView viewWithFrame:[window bounds]
								   pixelFormat:kEAGLColorFormatRGB565	// kEAGLColorFormatRGBA8
								   depthFormat:0						// GL_DEPTH_COMPONENT16_OES
						];
	
	// attach the openglView to the director
	[director setOpenGLView:glView];
	
//	// Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
//	if( ! [director enableRetinaDisplay:YES] )
//		CCLOG(@"Retina Display Not supported");
	
	//
	// VERY IMPORTANT:
	// If the rotation is going to be controlled by a UIViewController
	// then the device orientation should be "Portrait".
	//
	// IMPORTANT:
	// By default, this template only supports Landscape orientations.
	// Edit the RootViewController.m file to edit the supported orientations.
	//
#if GAME_AUTOROTATION == kGameAutorotationUIViewController
	[director setDeviceOrientation:kCCDeviceOrientationPortrait];
#else
	[director setDeviceOrientation:kCCDeviceOrientationLandscapeLeft];
#endif
	
	[director setAnimationInterval:1.0/30];
	//[director setDisplayFPS:YES];
	
	
	// make the OpenGLView a child of the view controller
	[viewController setView:glView];
	
	// make the View Controller a child of the main window
	[window addSubview: viewController.view];
	
	[window makeKeyAndVisible];
	
	// Default texture format for PNG/BMP/TIFF/JPEG/GIF images
	// It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
	// You can change anytime.
	[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];

	
	// Removes the startup flicker
	[self removeStartupFlicker];
	
	//[[SoundManager sharedManager] loadSound:@"EmoteClap2" ofType:@"mp3" withName:@"hit"];
	//[[SoundManager sharedManager] loadSound:@"playing" ofType:@"mp3" withName:@"background"];
	[[SoundManager sharedManager] loadSound:@"menu" ofType:@"mp3" withName:@"background_menu"];
	[[SoundManager sharedManager] loadSound:@"back" ofType:@"wav" withName:@"back"];
	[[SoundManager sharedManager] loadSound:@"clear" ofType:@"wav" withName:@"clear"];
	[[SoundManager sharedManager] loadSound:@"click" ofType:@"wav" withName:@"click"];
	[[SoundManager sharedManager] loadSound:@"drop" ofType:@"wav" withName:@"drop"];
	[[SoundManager sharedManager] loadSound:@"enter" ofType:@"wav" withName:@"enter"];
	[[SoundManager sharedManager] loadSound:@"failed" ofType:@"wav" withName:@"failed"];
	[[SoundManager sharedManager] loadSound:@"lock" ofType:@"wav" withName:@"lock"];
	[[SoundManager sharedManager] loadSound:@"retry" ofType:@"wav" withName:@"retry"];
	[[SoundManager sharedManager] loadSound:@"cgsys07" ofType:@"wav" withName:@"mode_select"];
	[[SoundManager sharedManager] loadSound:@"cgsys01" ofType:@"wav" withName:@"option_change"];
	[[SoundManager sharedManager] loadSound:@"bomb" ofType:@"wav" withName:@"bomb"];
	[[SoundManager sharedManager] loadSound:@"throw" ofType:@"wav" withName:@"throw"];

	[[CCDirector sharedDirector] setProjection:kCCDirectorProjection2D];

	NSString *path = [CCFileUtils fullPathFromRelativePath:@"game_config.plist"];
	NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
	
	sound_on = [[dict objectForKey:@"sound"] boolValue];	
	music_on = [[dict objectForKey:@"music"] boolValue];
	game_center_on = [[dict objectForKey:@"game center"] boolValue];;
	if (game_center_on) {
		[[GameCenter sharedGameCenter] authenticatePlayer];
	}
	// Run the intro Scene
	[[CCDirector sharedDirector] runWithScene: [HelloWorldLayer scene]];
}


- (void)applicationWillResignActive:(UIApplication *)application {
	[[CCDirector sharedDirector] pause];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
	[[CCDirector sharedDirector] resume];
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
	[[CCDirector sharedDirector] purgeCachedData];
}

-(void) applicationDidEnterBackground:(UIApplication*)application {
    [[GameLogic sharedGameLogic] save];
    
	CCScene * scene = [[CCDirector sharedDirector] runningScene];
	CCNode * layer = [scene.children objectAtIndex:0];
	if ([layer isKindOfClass:[playLayer class]]) {	
		// 1. 一个 CCRenderTexture 用以存储当前场景(你就是要在这上面弹出界面)的界面
		CGSize winSize = [[CCDirector sharedDirector] winSize];
		CCRenderTexture* renderTexture = [CCRenderTexture renderTextureWithWidth:winSize.width height:winSize.height];
		[renderTexture begin];
		[scene visit];
		[renderTexture end];
		[renderTexture setPosition:ccp(winSize.width/2, winSize.height/2)];
	
		//2. pauseScene 是要弹出的界面场景，看起来还有上一个界面，实际上已经切换了一个场景
		CCScene* pauseScene = [CCScene node];
		//3. 一个 CCLayerColor/CCColorLayer （这两个一样） 用以在上一个界面覆盖一层, 实现暗灰效果
		CCLayerColor* colorLayer = [CCLayerColor layerWithColor:ccc4(0, 0, 0, 200)];
		// pauseScene 的组成：从底层向外层： 上一个界面截图，暗灰效果层, 新的弹出菜单层。
		[pauseScene addChild:renderTexture];
		[pauseScene addChild:colorLayer];
		[pauseScene addChild:[pauseLayer node]];
		// 4. 直接 push 过去吧，方便存储当前场景状态之类的
		[[CCDirector sharedDirector] pushScene:pauseScene];	
	}
	
	[[CCDirector sharedDirector] stopAnimation];
}

-(void) applicationWillEnterForeground:(UIApplication*)application {
	[[CCDirector sharedDirector] startAnimation];
}

- (void)applicationWillTerminate:(UIApplication *)application {
	CCDirector *director = [CCDirector sharedDirector];
	
	[[director openGLView] removeFromSuperview];
	
	[viewController release];
	
	[window release];
	
	[director end];	
}

- (void)applicationSignificantTimeChange:(UIApplication *)application {
	[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
}

- (void)dealloc {
	[[CCDirector sharedDirector] release];
	[window release];
	[super dealloc];
}

@end
